#include "renderer.h"
#include <QDebug>
#include <QFile>
#include <QOpenGLBuffer>
#include <QOpenGLShaderProgram>

Renderer::Renderer(QWidget *parent) :
    QGLViewer(parent)
{

}

Renderer::~Renderer()
{

}

void Renderer::init()
{
    createObjects();
    setupLighting();

    glClearColor(0.5, 0.5, 0.5, 1.0);
    glEnable(GL_DEPTH_TEST);
}


void Renderer::draw()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    for(int i = 0; i < _objects.size(); ++i)
       _objects[i]->draw();



    //    qDebug() << "In Draw!";
//    // Draws a spiral
//    const float nbSteps = 200.0;
//    glBegin(GL_QUAD_STRIP);
//    for (float i=0; i<nbSteps; ++i)
//      {
//        float ratio = i/nbSteps;
//        float angle = 21.0*ratio;
//        float c = cos(angle);
//        float s = sin(angle);
//        float r1 = 1.0 - 0.8*ratio;
//        float r2 = 0.8 - 0.8*ratio;
//        float alt = ratio - 0.5;
//        const float nor = .5;
//        const float up = sqrt(1.0-nor*nor);
//        glColor3f(1.0-ratio, 0.2f , ratio);
//        glNormal3f(nor*c, up, nor*s);
//        glVertex3f(r1*c, alt, r1*s);
//        glVertex3f(r2*c, alt+0.05, r2*s);
//      }
//    glEnd();
}



void Renderer::createObjects()
{
    SceneObject *object = new SceneObject();
    object->readObjFile(":/teapot.obj");
    if(object->normals().size() == 0)
        object->calculateNormalsFromFaces();
    object->debugOutput(0);
    object->createBuffers();
    object->createShaderProgram();

    _objects.push_back(object);
}



void Renderer::setupLighting()
{

    // Set lighting information
    _light._position = QVector4D( -0.8f, .8f, 0.0f, 1.0f ) ;
    _light._intensity = QVector3D( 1.0f, 1.0f, 1.0f ) ;

    for(int i = 0; i < _objects.size(); ++i)
    {
        _objects[i]->setupLighting(_light);
    }
}

